package com.web;

import java.io.InputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

//@Component
public class NetWork {

	public static void main(String[] args) throws Exception {
		
		Map<String, Object> newProfile = new HashMap<>();
		newProfile.putAll(null);
		
//		test1();
//		test2();
	}

	static void test2() throws Exception {
		RestTemplate restTemplate = restTemplate();

		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/x-www-form-urlencoded");
		headers.add("Accept", "application/json");
		headers.add("Cookie", "SESSION=054c6e0e-dc9c-4b22-b52d-53518dba8a4f");

		// 使用map,涉及到MessageConvert的问题,可以直接转为String比较合适
		Map<String, Object> params = new HashMap();
		params.put("serialNumber", "");
		params.put("tradeId", "");
		params.put("custName", "");
		params.put("providerCode", "");
		params.put("startDate", "");
		params.put("endDate", "");
		params.put("tradeTypeCode", "");
		params.put("enterpriseName", "");
		params.put("acceptStaffId", "");
		params.put("pageNum", 1);
		params.put("pageSize", 10);
		params.put("flag", 2);

//		UriComponentsBuilder builder = UriComponentsBuilder
//				.fromUriString("https://crm.10039.cc/crm/VCommonController/checkCust").queryParam("param",
//						"{\"provinceCode\":\"8360000\",\"regionCode\":\"8361100\",\"qryMode\":\"0\",\"serialNumber\":\"13261208707\",\"queryType\":\"null\",\"tradeTypeCode\":\"90\"}");

		HttpEntity<String> entity = new HttpEntity<>(
				"serialNumber=&tradeId=&custName=&providerCode=&startDate=&endDate=&tradeTypeCode=&enterpriseName=&acceptStaffId=&pageNum=1&pageSize=10&flag=2",
				headers);

		// 解决{}被认为是占位符的问题
		String json = "{\"provinceCode\":\"8360000\",\"regionCode\":\"8361100\",\"qryMode\":\"0\",\"serialNumber\":\"13232222222\",\"queryType\":\"null\",\"tradeTypeCode\":\"90\"}";
		ResponseEntity<String> responseEntity = restTemplate.exchange(
				"https://crm.10039.cc/crm/createAccountController/qryInNetStoreTrade", HttpMethod.POST, entity,
				new ParameterizedTypeReference<String>() {
				}, json);

		System.out.println(responseEntity.getStatusCodeValue());

		if (responseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
			System.out.println(responseEntity);
		}
	}

	static void test1() throws Exception {
		RestTemplate restTemplate = restTemplate();

		HttpHeaders headers = new HttpHeaders();
		headers.add("Accept", "application/json");
		headers.add("Cookie", "SESSION=054c6e0e-dc9c-4b22-b52d-53518dba8a4f");

//		UriComponentsBuilder builder = UriComponentsBuilder
//				.fromUriString("https://crm.10039.cc/crm/VCommonController/checkCust").queryParam("param",
//						"{\"provinceCode\":\"8360000\",\"regionCode\":\"8361100\",\"qryMode\":\"0\",\"serialNumber\":\"13261208707\",\"queryType\":\"null\",\"tradeTypeCode\":\"90\"}");

		HttpEntity entity = new HttpEntity(headers);

		String json = "{\"provinceCode\":\"8360000\",\"regionCode\":\"8361100\",\"qryMode\":\"0\",\"serialNumber\":\"13232222222\",\"queryType\":\"null\",\"tradeTypeCode\":\"90\"}";
		ResponseEntity<String> responseEntity = restTemplate.exchange(
				"https://crm.10039.cc/crm/VCommonController/checkCust?param={json}", HttpMethod.GET, entity,
				new ParameterizedTypeReference<String>() {
				}, json);

		System.out.println(responseEntity.getStatusCodeValue());

		if (responseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
			System.out.println(responseEntity);
		}
	}

	/**
	 * 带网站证书的restTemplate
	 * 
	 * @return
	 * @throws Exception
	 */
	static RestTemplate restTemplate() throws Exception {
		HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
		factory.setConnectionRequestTimeout(5 * 60 * 1000);
		factory.setConnectTimeout(5 * 60 * 1000);
		factory.setReadTimeout(5 * 60 * 1000);
		// https
		SSLContextBuilder builder = new SSLContextBuilder();
		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		ClassPathResource resource = new ClassPathResource("xx.keystore");
		InputStream inputStream = resource.getInputStream();
		keyStore.load(inputStream, null);
		SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(),
				NoopHostnameVerifier.INSTANCE);
		Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http", new PlainConnectionSocketFactory()).register("https", socketFactory).build();
		PoolingHttpClientConnectionManager phccm = new PoolingHttpClientConnectionManager(registry);
		phccm.setMaxTotal(200);
		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory)
				.setConnectionManager(phccm).setConnectionManagerShared(true).build();
		factory.setHttpClient(httpClient);
		RestTemplate restTemplate = new RestTemplate(factory);
		List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
		ArrayList<HttpMessageConverter<?>> convertersValid = new ArrayList<>();
		for (HttpMessageConverter<?> converter : converters) {
			if (converter instanceof MappingJackson2HttpMessageConverter
					|| converter instanceof MappingJackson2XmlHttpMessageConverter) {
				continue;
			}
			convertersValid.add(converter);
		}
		MappingJackson2HttpMessageConverter httpMessageConverter = new MappingJackson2HttpMessageConverter();
		convertersValid.add(httpMessageConverter);
		restTemplate.setMessageConverters(convertersValid);
		inputStream.close();
		return restTemplate;
	}

}
